import { defineStore } from 'pinia';
import { ref, onMounted } from 'vue';
import { chartList, addChat, getMsg } from '@/apis/ws';
import { ElMessage } from 'element-plus';
import { userInfoStore } from './user';
import { MessageFactory } from '@/utils/socket';

export const useChatStore = defineStore('chat', () => {
  // 状态定义
  const conversations = ref([]); // 会话列表
  const currentConversation = ref(null); // 当前会话 ID
  const messages = ref([]); // 消息列表
  const unread = ref(0) // 未读数
  const newMessage = ref(''); // 新消息
  const wsConnected = ref(false); // WebSocket 连接状态
  const ws = ref(null); // WebSocket 实例

  const setNewMessage = (val) => {
    newMessage.value = val
  }


  // 初始化 WebSocket 连接
  const initWebSocket = () => {
    const wsUrl = import.meta.env.VITE_APP_WEB_BASE_TARGET_WS;
    ws.value = new WebSocket(wsUrl + `/${userInfoStore().userInfo.userId}`);

    ws.value.onopen = () => {
      console.log('ws.value: onopen ', ws.value);
      wsConnected.value = true;
      console.log(' wsConnected.value: onopen ', wsConnected.value);
      ElMessage.success('开启聊天');
    };

    ws.value.onerror = (error) => {
      wsConnected.value = false;
      ElMessage.error(`连接错误: ${error.message}`);
    };

    ws.value.onmessage = (event) => {
      console.log('event: onmessage ', event);
      if (event.data) {
        // const message = MessageFactory.parseMessage(event.data);
        // addMessage(message);
        const message = JSON.parse(event.data)

        console.log('Received message:', message);

        if (message.type === 'UNREAD') {
          unread.value = message.count
        } else if (message.type === 'text') {
          const data = MessageFactory.parseMessage(event.data)
          addMessage(data);
        } else if (message.type === 'file') {
          const data = MessageFactory.parseMessage(event.data);
          addMessage(data);
        }
      }
    };

    ws.value.onclose = () => {
      wsConnected.value = false;
      console.log('wsConnected.value: onclose ', wsConnected.value);
      // ElMessage.warning('结束聊天');
    };
  };

  // 创建会话
  const createConversation = async (participantId) => {
    try {
      const res = await addChat({
        type: 'PERSONAL',
        participants: [userInfoStore().userInfo.userId, participantId],
      });
      if (res.code === 200) {
        currentConversation.value = res.conversationId;
        return res.conversationId;
      } else {
        ElMessage.error('会话创建失败');
        return null;
      }
    } catch (error) {
      ElMessage.error('会话创建失败');
      console.error(error);
      return null;
    }
  };

  // 获取会话列表
  const fetchConversations = async () => {
    try {
      const res = await chartList();
      if (res.code === 200) {
        conversations.value = res.data;
        return res.data;
      } else {
        ElMessage.error('获取会话列表失败');
        return [];
      }
    } catch (error) {
      ElMessage.error('获取会话列表失败');
      console.error(error);
      return [];
    }
  };

  // 获取会话消息
  const fetchMessages = async (data) => {
    try {
      const res = await getMsg({ conversationId: currentConversation.value, userId: userInfoStore().userInfo.userId, ...data });
      console.log('res: 获取会话消息 ', res);
      if (res.code === 0) {
        messages.value = res.rows.map((msg) => MessageFactory.parseMessage(JSON.stringify(msg)));
        return res.rows;
      } else {
        ElMessage.error('获取消息失败');
        return [];
      }
    } catch (error) {
      ElMessage.error('获取消息失败');
      console.error(error);
      return [];
    }
  };

  // 发送消息
  const sendMessage = (participantId) => {
    if (newMessage.value.trim() === '') return;
    console.log(' currentConversation.value: ', currentConversation.value);
    const messageData = MessageFactory.createTextMessage(
      currentConversation.value,
      userInfoStore().userInfo.userId,
      // userInfoStore().userInfo.userId,
      participantId,
      newMessage.value,
    );

    console.log('messageData: ', messageData);
    console.log('ws.value && wsConnected.value: ', ws.value && wsConnected.value);
    if (ws.value && wsConnected.value) {
      ws.value.send(JSON.stringify(messageData));
      addMessage(messageData);
      newMessage.value = '';
    } else {
      ElMessage.error('WebSocket 连接未建立');
    }
  };

  // 添加消息到列表
  const addMessage = (message) => {
    messages.value.push(message);
  };

  // 关闭 WebSocket 连接
  const closeWebSocket = () => {
    if (ws.value) {
      ws.value.close();
    }
  };


  return {
    conversations,
    currentConversation,
    messages,
    newMessage,
    wsConnected,
    initWebSocket,
    createConversation,
    fetchConversations,
    fetchMessages,
    sendMessage,
    addMessage,
    closeWebSocket,
    setNewMessage
  };
});